package com.laikan.reader.apirequester;

import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.BeanComparator;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.BookNetUtils;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.*;

/**
 * Created by anrun on 7/27/16.
 * 书架的网络请求对象
 */
public class BookShelfRequester {

    /*
    * 从网络获取书架列表数据
    */
    public static void syncBookFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("syncBookFromServer--------------------------------------");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<BaseListDataBean<Book>> result;

                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<Book>>>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if ("0".equals(result.getResult())) {
                        ToastMgr.showShortToast(result.getError_msg());
                    }else if (Constants.RESULT_OK.equals(result.getResult())) {

                        List<Book> netBooks = result.getData().getBookList();  //网络返回的书集合
                        List<Book> localBooks = DBBook.getInstance().queryAllBook();    //本地数据库中的书
                        List<Book> localUpBooks = new ArrayList<>();    //本地需要升级目录的书
                        HashMap<String, Book> localHashMapBooks = new HashMap<>();    //本地需要升级目录的书
                        for (Book localBook : localBooks) {
                            localHashMapBooks.put(localBook.getId(), localBook);
                        }

                        for (Book netBbook : netBooks) {
                            Book localBook = localHashMapBooks.get(netBbook.getId());
                            if (localBook != null && localBook.getIsUpdated()) {
                                netBbook.setIsUpdated(true);
                            }

                            DBBook.getInstance().insertBook(netBbook);
                        }
                        //                        netBooks.retainAll(localBooks); //取交集
                        for (Book netBbook : netBooks) {
                            Book localBook = localHashMapBooks.get(netBbook.getId());
                            if (localBook != null && !TextUtils.isEmpty(netBbook.getUpdateTime()) && !TextUtils.isEmpty(localBook.getUpdateTime()) && Long.parseLong(netBbook
                                .getUpdateTime()) >
                                                                                                                                                      Long.parseLong(localBook.getUpdateTime())) {
                                netBbook.setIsUpdated(true);
                                localUpBooks.add(netBbook);
                                KLog.e("update netBbook : name " + netBbook.getName() + " newUpdatetime: " + netBbook.getUpdateTime());
                            }
                        }

                        netBooks.clear();
                        localBooks.clear();
                        BookNetUtils.uploadBookshelfToServer(); //本地书籍同步到网络
                        LaiKanEvent event = LaiKanEvent.getInstance();
                        event.setEventID(LaiKanEvent.EVENT_ID_UPDATA_SUCCESS);
                        Map<String, Object> mapEvent = new HashMap<>();
                        mapEvent.put("localData", localUpBooks);
                        BasicApplication.postEvent(event.setEventMap(mapEvent));
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }finally {
                    LaiKanEvent event = LaiKanEvent.getInstance();
                    event.setEventID(LaiKanEvent.EVENT_ID_DISMISS_LOADING);
                    BasicApplication.postEvent(event);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                //                KLog.e(errorHandler.errorCode);
                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(LaiKanEvent.EVENT_ID_DISMISS_LOADING);
                BasicApplication.postEvent(event);
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_bookshelf + "?sd=" + SPUtil.getString("token", ""));
//        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
//        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.laikan_get_bookshelf + "?sd=" + SPUtil.getString("token", ""), null, null, requestListener);
    }

    /**
     * 安装完apk 后访问的接口,获取需要预装的书
     */
    public static void preBook(String specialBookId) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        if (specialBookId != null) {

            map.put("bookId", specialBookId); //1代表男频, 2女频, 3出版
        }
        map.put("group", SPUtil.getInt("current_channel", 3) + ""); //1代表男频, 2女频, 3出版

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<BaseListDataBean<Book>> result;
                Gson gson = new Gson();

                Type type = new TypeToken<BaseDataBean<BaseListDataBean<Book>>>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);

                    if (result != null) {
                        if (result.getData() == null || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            ArrayList<Book> mData = result.getData().getData();

                            // 合并网络数据
                            for (int j = 0; j < mData.size(); j++) {
                                DBBook.getInstance().insertBook(mData.get(j));
                            }
                            mData.clear();
                            SPUtil.putBoolean("yuZhangBook", false);
                            LaiKanEvent event = LaiKanEvent.getInstance();
                            event.setEventID(LaiKanEvent.EVENT_ID_READ_PRE_BOOK);
                            BasicApplication.postEvent(event);
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                KLog.e("网络不给力，请重试。70");
            }

            @Override
            public void onFinish() {

            }
        };
        if (specialBookId != null) {

            Requester requester = new Requester();
            requester.setUrl(APIProtocol.laikan_get_specialbook);
            requester.setMapBody(map);
            HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
        }else {

            Requester requester = new Requester();
            requester.setUrl(APIProtocol.laikan_get_indexbook);
            requester.setMapBody(map);
            HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
        }
    }

    /**
     * 根据bookid删除书籍列表中的书籍
     *
     * @param id bookid
     */
    public static void deleteData(String id) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        SPUtil.putBoolean("push_book", true);
                        ToastMgr.showShortToast("删除成功");
                    }
                }catch (JSONException e) {
                    ToastMgr.showShortToast("解析失败01");
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast("删除失败,服务器连接异常");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_follow + id + "/2/del?");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_follow + id + "/2/del?", map, null, null, requestListener);
    }

    /**
     * 删除该账号服务端的数据
     *
     * @param it
     */
    public static void deleteBookData(Iterator<String> it) {
        // 接口地址
        String url = APIProtocol.getRootURL2() + "follow_book_remove";
        StringBuilder buider = new StringBuilder();
        // 请求参数
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        while (it.hasNext()) {
            buider.append(it.next() + ":");
        }
        String bookIdParams = buider.toString().substring(0, buider.toString().length() - 1); //去除最后的分隔符 ：
        map.put("delBookId", bookIdParams);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {

                        ToastMgr.showShortToast("删除成功");
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(url);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(url, map, null, null, requestListener);
    }

    /**
     * 按照更新时间排序
     */
    private static BeanComparator<Book> sortBooksByTime() {
        return new BeanComparator<Book>() {
            @Override
            public int compare(Book bb1, Book bb2) {
                return bb2.getUpdateTime().compareTo(bb1.getUpdateTime());
            }
        };
    }

    /**
     * 根据bookid下载该书籍的目录
     *
     * @param bookid
     */
    public static void loadDirectory(final String bookid) {
        HashMap map = new HashMap();
        map.put("userId", SPUtil.getString("user_id", "0"));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                String json = httpResponse.responseContent;
                BaseDataBean<BaseListDataBean<ChapterBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ChapterBean>>>() {}.getType();
                try {
                    result = gson.fromJson(json, type);
                    // 记录最后章节id
                    ArrayList<ChapterBean> data = result.getData().getData();
                    SPUtil.putString(bookid + "_lastChapterId", data.get(data.size() - 1).getId());
                    BookFileUtils.totalChapter(bookid, data);
                }catch (Exception e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
                if (null == result || null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                    ToastMgr.showShortToast(result.getError_msg());
                }else {
                    BookFileUtils.totalChapter(bookid, result.getData().getData());
                    BookFileUtils.saveBookDirectory(json, bookid);
                }

                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(LaiKanEvent.EVENT_ID_LOAD_DIRECTORY);
                BasicApplication.postEvent(event);
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("1147 网络不给力，请重试。68");
            }

            @Override
            public void onFinish() {

            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "/book/" + bookid + "/chapter?");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.getRootURL() + "/book/" + bookid + "/chapter?", map, null, requestListener);
    }
}
